<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名字" width="120">
			</el-table-column>
			<el-table-column prop="tel" label="电话" width="180" sortable>
			</el-table-column>
			<el-table-column prop="registerTime" label="注册时间" width="180" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" min-width="80">
				<template slot-scope="scope">
					<span v-if="scope.row.state == 1" style="color: blue;">待审核</span>
					<span v-if="scope.row.state == 2" style="color: black;">审核通过待激活</span>
					<span v-if="scope.row.state == 3" style="color: green;">激活成功</span>
					<span v-if="scope.row.state == 4" style="color: red;">驳回</span>
				</template>
			</el-table-column>
			<el-table-column prop="address" label="地址" min-width="120" sortable>
			</el-table-column>
			<el-table-column prop="logo" label="logo" min-width="120" sortable>
			</el-table-column>
			<el-table-column prop="admin.username" label="管理员" width="100">
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
					layout="prev, pager, next"
					@current-change="handleCurrentChange"
					:page-size="query.pageSize"
					:total="pageInfo.total"
					:current-page="query.currentPage"
					style="float:right;">
			</el-pagination>
		</el-col>

		<!--
		新增/修改界面
		v-model="saveFormVisible"  这个它也是用来展示弹框的,但是现在已经过时了
		要换成  :visible.sync=
		:rules= 绑定校验规则
		 prop="name" 取校验规则中的某一个,
		-->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="名字" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">
					<el-select v-model="saveForm.manager.id" placeholder="请选择">
					<el-option
							v-for="item in employees"
							:key="item.id"
							:label="item.username"
							:value="item.id">
					</el-option>
				</el-select>
				</el-form-item>
				<el-form-item label="父部门">
					<el-cascader v-model="saveForm.parent"
								 :options="deptTree"
								 :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
								 clearable></el-cascader>
				</el-form-item>
				<el-form-item label="描述">
					<el-input type="textarea" v-model="saveForm.intro"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
					name: ''
				},
				Departments: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				saveFormVisible: false,//新增界面是否显示
				addLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入名字', trigger: 'blur' }
					]
				},
				//新增/修改-界面数据
				saveForm: {
					id:null,
					name: '',
					intro:"",
					state:null,
					manager:{
						id:null,
						username:""
					},
					parent:{
						id:null,
						name:""
					}
				},
				query:{
					currentPage:1,  // 当前页
					pageSize:10, // 每页显示条数
					keyword:""  // 关键字-查询条件
				},
				pageInfo:{
					total:0,  // 总条数
					rows:[] // 当前页数据
				},
				employees:[],
				deptTree:[]

			}
		},
		methods: {
			search(){
				// 将当前页设置为1
				this.query.currentPage = 1;
				this.getDepartments();
			},
			handleCurrentChange(val) {  // 当 当前页的值被改变时触发
				// 将val(当前页)赋值给query.currentPage
				this.query.currentPage = val;
				// 调用查询方法,重新查询
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				console.log(this.query)
				// 调用后端接口查询数据
				// "/department" 如果直接写这个路径,它默认是访问80的一个路径 需要需要在main.js中,引入axios时配置基本路径axios.defaults.baseURL
				// this.$http.post("/department"  = axios.baseURL+/department = http://localhost:8080/department
				this.$http.post("/department",this.query)
						.then(result => { // 后端操作成功,进入then()
							console.log(result);
							result = result.data; // {success:true,message:"",dataObj:{}}
							if(result.success){ // true 后端返回了数据
								this.pageInfo = result.data;
							}else{ // false 说明后端处理失败
								this.$message({message: result.message,type: 'error'});
							}
						})
						.catch(result => {  // 如果报错 就会进入catch()
							this.$message({message: "网络异常,请检查网络!",type: 'error'});
						})
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除这个数据吗?', '提示', {
					type: 'warning'
				}).then(() => {
					// 1 获取当前要删除数据的ID
					let id = row.id;
					// 2 调后端的删除接口
					this.$http.delete("/department/"+id)
							.then(result => {
								result = result.data; // {success:true,message:""}
								if(result.success){
									// 提示"删除成功"
									this.$message({message: "删除成功!",type: 'success'});
									// 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
									this.query.currentPage = 1;
									// 调用查询方法
									this.getDepartments();
									// this.search();
								}else{
									this.$message({message: result.message,type: 'error'});
								}
							})
							.catch(result => {
								this.$message({message: "网络异常,请检查网络!",type: 'error'});
							})
				}).catch(() => {
					this.$message({message: '已取消删除!',type: 'info'});
				});
			},

			getdeptTree:function(){
				this.$http.get("/department/tree")
				.then(result=>{
					result=result.data
					this.deptTree=result.data
				}).catch(result=>{
					this.$message({message: "网络异常,请检查网络!",type: 'error'});
				})

			},
			getemployees: function(){
				this.$http.get("/employee")
				.then(result=>{
					result=result.data
					if (result.success){
						this.employees=result.data
					}else {
						this.$message({message: "网络异常,请检查网络!",type: 'error'});
					}
				}).catch(result=>{
					this.$message({message: "网络异常,请检查网络!",type: 'error'});
				})
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				// 展示弹框
				this.saveFormVisible = true;
				// 将当前行的对象赋值给this.saveForm对象
				this.saveForm = Object.assign({}, row);
				console.log(this.saveForm);
				// 特殊处理manager parent
				// 如果manager parent没有值,为null的话,就给它们赋一个初识对象
				if(!this.saveForm.manager){
					this.saveForm.manager = {
						id:null,
						username: ""
					}
				}
				let temp=[];
				if(!this.saveForm.parent){
					this.saveForm.parent = {
						id:null,
						name: ""
					}
				}else {
					let arr=row.path.split("/")
					console.log(arr)
					for(let i=1;i<arr.length-1;i++){
						temp.push(parseInt(arr[i]))
					}
				}
				this.saveForm.parent=temp
				this.getemployees()
				this.getdeptTree()
			},
			//显示新增界面
			handleAdd: function () {
				// 显示弹框
				this.saveFormVisible = true;
				// 初始化弹框的值,为了防止将上次的内容带到了下一次
				this.saveForm = {
					id:null,
					name: '',
					intro:"",
					state:null,
					manager:{
						id:null,
						username:""
					},
					parent:{
						id:null,
						name:""
					}
				};
				this.getemployees()
				this.getdeptTree()
			},
			//编辑
			editSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.saveForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editUser(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['saveForm'].resetFields();
								this.saveFormVisible = false;
								this.getDepartments();
							});
						});
					}
				});
			},
			//新增/修改的保存
			save: function () {
				// this.$refs.saveForm.validate((valid) => { 校验表单是否满足校验规则 valid=true 满足校验规则
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true; // 加载框
							console.log(this.saveForm)
							let param=this.saveForm
							if(param.parent){
								param.parent = {"id":param.parent[param.parent.length-1]}
							}
							// 调用后端接口-axios
							this.$http.put("/department",param)
									.then(result => {
										// 获取后端返回的结果
										result = result.data; // {success:true,message:""}
										if(result.success){
											this.$message({message: "保存成功!",type: 'success'});
											// 关闭弹框
											this.saveFormVisible = false;

											// 关闭加载框
											this.addLoading = false;

											// 重新查询数据-(从当前页查询还是回到第一页,看需求)
											this.query.currentPage = 1;
											this.getDepartments();
										}else{
											this.$message({message: result.message,type: 'error'});
										}
									})
									.catch(result => {
										this.$message({message: "网络异常,请检查网络!",type: 'error'});
									})
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				// 1 获取选中的要删除行的ID
				var ids = this.sels.map(item => item.id);
				console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					// 2 调后端的删除接口
					this.$http.patch("/department",ids)
							.then(result => {
								result = result.data; // {success:true,message:""}
								if(result.success){
									// 提示"删除成功"
									this.$message({message: "删除成功!",type: 'success'});
									// 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
									this.query.currentPage = 1;
									// 调用查询方法
									this.getDepartments();
									// this.search();
								}else{
									this.$message({message: result.message,type: 'error'});
								}
							})
							.catch(result => {
								this.$message({message: "网络异常,请检查网络!",type: 'error'});
							})
				}).catch(() => {
					this.$message({message: '已取消删除!',type: 'info'});
				});
			}
		},
		mounted() {
			// 挂载完毕,就要去后端查询分页数据并展示
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>